﻿using Markdig;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore.Metadata.Internal;
using NewsEntity.Models;
using NewsSevicer.Interface;
using NewsSevicer.ResultClass;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
using System.Web;

namespace NewsSevicer
{
    public class AdminServer : IAdminServer
    {
        private NewsContext _context;
        public AdminServer(NewsContext newsContext)
        {
            _context = newsContext;

        }




        public ResultData GetBannerInfo(string url)
        {

            var query = (from d in _context.BannerManager
                         select new BannerManager
                         {
                             ID = d.ID,
                             Image = url + d.Image,
                             Remark = d.Remark,
                             Url = d.Url,
                             AddTime = d.AddTime

                         }).ToList();

            return new ResultData { code = 200, message = "拿到数据了", data = query };

        }



        /// <summary>
        /// 删除banner
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public bool DelectBanner(BannerManager bannerManager)
        {

            var banner = _context.BannerManager.Find(bannerManager.ID);
            _context.BannerManager.Remove(banner);
            int result = _context.SaveChanges();
            if (result == 1)
            {
                return true;
            }
            return false;

        }

        public ResultData AddNews(News news)
        {

            if (news != null)
            {
                news.PublishDate = DateTime.Now;
                //设置新闻状态
                news.NewsStatus = 0;
                _context.News.Add(news);
                int result = _context.SaveChanges();
                if (result > 0)
                {
                    return new ResultData { code = 200, message = "添加新闻成功", data = null };

                }
            }
            return new ResultData { code = 500, message = "添加新闻失败了", data = null };

        }

        /// <summary>
        /// 添加新闻类别
        /// </summary>
        /// <param name="newsType"></param>
        /// <returns></returns>
        public ResultData AdminAddNewsType(NewsType newsType)
        {
            _context.NewsType.Add(newsType);
            int result = _context.SaveChanges();

            if (result > 0)
            {

                return new ResultData
                {
                    code = 200,
                    message = "插入成功",
                    data = null

                };
            }
            return new ResultData
            {
                code = 200,
                message = "插入成功",
                data = null

            };

        }
        /// <summary>
        /// 删除新闻类别
        /// </summary>
        /// <returns></returns>

        public ResultData DeleteNewsType(int typeid)
        {
            NewsType NewType = _context.NewsType.Find(typeid);

            _context.NewsType.Remove(NewType);
            int result = _context.SaveChanges();
            if (result > 0)
            {
                return new ResultData { code = 200, message = "删除成功", data = null };

            }
            return new ResultData { code = 500, message = "删除失败", data = null };

        }

        /// <summary>
        /// 获取新闻类别数据
        /// </summary>
        /// <returns></returns>
        public ResultData GetNewsType()
        {
            var datas = _context.NewsType.ToList();

            if (datas.Count() > 0)
            {
                return new ResultData
                {
                    code = 200,
                    message = "请求数据成功",
                    data = datas


                };
            }
            return new ResultData
            {
                code = 500,
                message = "请求数据成功",
                data = null


            };


        }

        /// <summary>
        /// 添加banner
        /// </summary>
        /// <param name="bannerManager"></param>
        /// <returns></returns>
        public bool AddBanner(BannerManager bannerManager)
        {

            _context.BannerManager.Add(bannerManager);
            int result = _context.SaveChanges();
            if (result == 1)
            {
                return true;

            }
            return false;
        }






        /// <summary>
        /// 获取所有新闻
        /// </summary>
        public Object GetAdminNews()
        {

            object list = (from t in _context.News
                           join y in _context.NewsType on t.InfoType equals y.TypeId
                           select new AdminNews
                           {
                               Id = t.Id,
                               TypeInfo = y.TypeName,
                               NewsTitle = t.NewsTitle,
                               NewsContent = t.NewsContent,
                               PublishDate = t.PublishDate.Value.ToString("yyyy年MM月dd日-H:mm"),
                               Remark = t.Remark,
                               Image = t.Image

                           }).ToList();
            return list;
        }



        /// <summary>
        /// 分页查询
        /// </summary>
        /// <param name="pageindex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        public ResultPaging NewsPaging(int pageindex, int pageSize)
        {

            var data = (from t in _context.News
                        join y in _context.NewsType on t.InfoType equals y.TypeId
                        select new AdminNews
                        {
                            Id = t.Id,
                            TypeInfo = y.TypeName,
                            NewsTitle = t.NewsTitle,
                            NewsContent = t.NewsContent,
                            PublishDate = t.PublishDate.Value.ToString("yyyy年MM月dd日-H:mm"),
                            Remark = t.Remark,
                            Image = t.Image

                        }).Skip((pageindex - 1) * pageSize).Take(pageSize);
            long count = _context.News.LongCount();
            //Math.Ceiling：向上进位取整。
            long pageCount = (long)Math.Ceiling(count * 1.0 / pageSize);

            return new ResultPaging { PagingData = data, pagingCount = pageCount };

        }


        /// <summary>
        /// 假删除新闻（隐藏）
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public int DelNews(News news)
        {
            try
            {
                News newss = _context.News.Find(news.Id);
                if (newss != null)
                {
                    // 将新闻状态设置为 2，表示删除状态
                    newss.NewsStatus = 2;
                    _context.SaveChanges();
                    return 1;
                }
                else
                {
                    // 处理未找到新闻的情况，例如返回特定错误码或抛出异常
                    return -1; // 表示未找到新闻
                }
            }
            catch (Exception ex)
            {
                // 记录异常日志或采取其他措施
                // 例如：_logger.LogError(ex, "An error occurred while deleting news.");
                Console.WriteLine($"An error occurred: {ex.Message}");
                return -1; // 表示操作失败
            }
        }

        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="adminlogin"></param>
        /// <returns></returns>

        public bool AdminLogin(Adminlogin adminlogin)
        {

            List<Adminlogin> adminlogin1 = _context.Adminlogin.Where(a => a.UserName.Equals(adminlogin.UserName.Trim()) && a.PassWord.Equals(adminlogin.PassWord.Trim())).ToList();
            if (adminlogin1.Count > 0)
            {
                return true;
            }
            return false;
        }
        /// <summary>
        /// 获取某个新闻分类下的新闻
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public List<News> GetTypeNews(int id)
        {

            List<News> news = _context.News.Where(m => m.InfoType == id).ToList();
            return news;
        }

        public ResultData GetEditNews(int id, string ip="")
        {
            //加密IP地址
          string encrypted  = XorCrypt.Crypt(ip);
            //string decrypted = XorCrypt.Crypt(encrypted);    // 解密
            try
            {
                if (id > 0)
                {
                    var query = _context.News.Find(id);
                    if (query != null)
                    {
                        if (!string.IsNullOrEmpty(ip)) {
                           var imgList = query.Image.Split(",");
                            imgList = imgList.Where(x=>!string.IsNullOrWhiteSpace(x)).ToArray();
                            //if (imgList.Length>0)
                            //{
                            //    for (int i = 0; i < imgList.Length; i++)
                            //    {
                            //        if (!string.IsNullOrEmpty(imgList[i]))
                            //            imgList[i] = ip + imgList[i];
                            //    }
                            //}
                          query.Image= string.Join(",", imgList);
                        }
                    }
                    //query.NewsContent = Markdown.ToHtml(query.NewsContent);
                    return new ResultData { code = 200, message = encrypted, data = query };
                }
                return new ResultData { code = 500, message = encrypted, data = null };
            }
            catch (Exception)
            {
                return new ResultData { code = 500, message = encrypted, data = null };

            }

        }

        private static class XorCrypt
        {
            public static string Crypt(string text)
            {
                string key = "xiaoweiIPKey"; // 密钥，可以根据需要更改
                StringBuilder result = new StringBuilder();
                for (int i = 0; i < text.Length; i++)
                {
                    // 循环使用密钥字符异或
                    char keyChar = key[i % key.Length];
                    result.Append((char)(text[i] ^ keyChar));
                }
                return result.ToString();
            }

        }
            /// <summary>
            /// 编辑新闻
            /// </summary>
            /// <param name="news"></param>
            /// <returns></returns>
            /// <exception cref="NotImplementedException"></exception>
            public bool EditNews(News news)
        {
            var query = _context.News.Find(news.Id);

            query.NewsContent = news.NewsContent;
            query.NewsTitle = news.NewsTitle;
            query.Image = news.Image;
            query.InfoType = news.InfoType;
            query.Remark = news.Remark;
            int result = _context.SaveChanges();
            if (result > 0)
            {
                return true;

            }
            return false;

        }


        public bool EditNewsContent(News news)
        {
            try
            {
                var query = _context.News.Find(news.Id);

                query.NewsContent = news.NewsContent;
                query.NewsStatus = news.NewsStatus;
                _context.SaveChanges();

                return true;
            }
            catch (Exception ex)
            {
                // 可以在这里处理异常情况，比如记录日志等
                Console.WriteLine($"编辑新闻内容时出错：{ex.Message}");
                return false;
            }
        }

        public bool EditNewsImages(News news)
        {
            try
            {
                var query = _context.News.Find(news.Id);

                query.Image = news.Image;
                _context.SaveChanges();

                return true;
            }
            catch (Exception ex)
            {
                // 可以在这里处理异常情况，比如记录日志等
                Console.WriteLine($"编辑新闻图片时出错：{ex.Message}");
                return false;
            }
        }


        /// <summary>
        /// 新闻评论的显示server
        /// </summary>
        /// <returns></returns>
        public ResultData ResultCommentModel()
        {
            var comment = (from t in _context.News
                           join c in _context.NewInfo on t.Id equals c.NewsId
                           select new CommentModel
                           {
                               NewsCommentId = c.Id,
                               NewsCommentContent = c.Content,
                               NewsTitle = t.NewsTitle,
                               NewsId = t.Id,
                               CreateDate = c.CreateTime.Value.ToString("yyyy年MM月dd日-H:mm"),



                           }

                          ).ToList();

            return new ResultData { code = 200, message = "拿到数据了", data = comment };

        }

        /// <summary>
        /// 删除新闻评论
        /// </summary>
        /// <param name="newsCommentId">新闻评论id</param>
        /// <returns></returns>
        public bool DelectComment(int newsCommentId)
        {
            try
            {
                var newscoment = _context.NewInfo.Find(newsCommentId);
                _context.NewInfo.Remove(newscoment);
                int result = _context.SaveChanges();
                if (result > 0)
                {
                    return true;
                }
                return false;
            }
            catch (Exception)
            {
                return false;

            }

        }


        public List<string> GetNewsimages(int id)
        {
            var news = _context.News.Find(id);
            // 原始字符串  


            // 使用Split方法将字符串按逗号分割成子字符串数组  
            string[] parts = news.Image.Split(',');
           var imagesList = parts.Where(p => !string.IsNullOrEmpty(p)).ToArray(); // 过滤掉空字符串
            // 将数组中的每个元素添加到List<string>中  
            List<string> imgagesList = new List<string>(imagesList);
            return imgagesList;

        }
        public string GetNewsimagesStr(int id)
        {
            var news = _context.News.Find(id);
            // 原始字符串  


            // 使用Split方法将字符串按逗号分割成子字符串数组  
            string[] parts = news.Image.Split(',');
            var imagesList = parts.Where(p => !string.IsNullOrEmpty(p)).ToArray(); // 过滤掉空字符串
            string result = string.Join(",", imagesList); // 输出："1,2,3"
            return result;
        }
        public int DelectNews(News news)
        {
            try
            {
                News newss = _context.News.Find(news.Id);
                if (newss != null)
                {
                    // 将新闻状态设置为 2，表示删除状态
                    _context.News.Remove(newss);
                    _context.SaveChanges();
                    return 1;
                }
                else
                {
                    // 处理未找到新闻的情况，例如返回特定错误码或抛出异常
                    return -1; // 表示未找到新闻
                }
            }
            catch (Exception ex)
            {
                // 记录异常日志或采取其他措施
                // 例如：_logger.LogError(ex, "An error occurred while deleting news.");
                Console.WriteLine($"An error occurred: {ex.Message}");
                return -1; // 表示操作失败

            }
        }

   
    }

}
